package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@WebFilter("/*")

@Slf4j

public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /**
         * 获取请求路径
         * 登录,放行
         * 不是登录, 验证token
         * +获取token
         * 验证token非空
         * 解析验证token,错误的就返回
         * 正确放行
         */
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getRequestURI();
        if (path.contains("login")) {
            log.info("登录操作: {}", path);
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.info("token为空:{}", token);
            response.setStatus(401);
            return;
        }
//        解析 token
        try {
         Claims claims = JwtUtils.parseToken(token);//
            log.info("token解析成功:{}", claims);
            Integer userid = claims.get("id", Integer.class);//存取id
            CurrentUserHoler.setCurrentUser(userid);
        } catch (Exception e) {
            log.info("token解析失败:{}", e.getMessage());
            response.setStatus(401);
            return;
        }
        filterChain.doFilter(request, response);
    }
}
